/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.pay.channels.wechat.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pub.pjoc.pay.channels.wechat.service.WeixinOrderService;
import pub.pjoc.pay.channels.wechat.service.WeixinPayConfigInfo;
import pub.pjoc.pay.channels.wechat.util.WeixinPayUtils;
import pub.pjoc.pay.channels.wechat.vo.OrderCallBackRequest;
import pub.pjoc.pay.channels.wechat.vo.OrderRequest;
import pub.pjoc.pay.channels.wechat.vo.OrderResponse;
import pub.pjoc.pay.channels.wechat.vo.ReturnResult;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;


/**
 * web interface
 * @author blademainer
 * @version 2016-08-02 14:20
 */
@Controller
@RequestMapping("/pay")
public class PayController {
  private static final Logger logger = LoggerFactory.getLogger(PayController.class);
  public static final String HAS_REQUEST_OAUTH = "PayController.HAS_REQUEST_OAUTH";
  @Autowired
  private WeixinPayConfigInfo configInfo;
  @Autowired
  private WeixinOrderService orderService;

  /**
   * 订单回调通知
   */
  @RequestMapping(value = "/callBack")
  @ResponseBody
  public ReturnResult callBack(HttpServletRequest servletRequest) {
    if (logger.isDebugEnabled()) {
      Enumeration<String> headerNames = servletRequest.getHeaderNames();
      while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        String header = servletRequest.getHeader(headerName);
        logger.debug("Doing call back... header: {}={}", headerName,
            header);
      }
    }

    OrderCallBackRequest request;

    try {
      XmlMapper xmlMapper = WeixinPayUtils.getXmlMapper();
      ServletInputStream inputStream = servletRequest.getInputStream();
      request = xmlMapper.readValue(inputStream, OrderCallBackRequest
          .class);
    } catch (IOException e) {
      logger.error("Caught exception when calling back! message: " + e
          .getMessage(), e);
      return null;
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Doing call back... call back: {}", request);
    }
    ReturnResult returnResult = orderService.doCallBack(request);
    if (logger.isDebugEnabled()) {
      logger.debug("Doing call back... returnResult: {}", returnResult);
    }
    return returnResult;
  }

  /**
   * 订单回调通知
   */
  @RequestMapping(value = "/callBack/xml", consumes = {MediaType
      .TEXT_XML_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType
      .APPLICATION_JSON_VALUE})
  @ResponseBody
  public ReturnResult callBackWithRequestBody(@RequestBody OrderCallBackRequest request) {
    if (logger.isDebugEnabled()) {
      logger.debug("Doing call back... call back: {}", request);
    }
    ReturnResult returnResult = orderService.doCallBack(request);
    if (logger.isDebugEnabled()) {
      logger.debug("Doing call back... returnResult: {}", returnResult);
    }
    return returnResult;
  }

  @RequestMapping(value = "/order")
  @ResponseBody
  public OrderResponse orderRequest(HttpServletRequest request, HttpSession session,
                                    OrderRequest orderRequest) {
    if (logger.isDebugEnabled()) {
      logger.debug("request query str: {}, orderRequest: {}", request
              .getQueryString(),
          orderRequest);
    }
    if (StringUtils.hasText(request.getRemoteAddr()) && StringUtils
        .isEmpty(orderRequest.getSpBillCreateIp())) {
      String remoteAddr = request.getRemoteAddr();
      orderRequest.setSpBillCreateIp(remoteAddr);
    }
    OrderResponse orderResponse = orderService.requestOrder(orderRequest);
    return orderResponse;
  }

  public static String getRequestUrlAndParameters(HttpServletRequest
                                                      request) {
    StringBuffer requestURL = request.getRequestURL();
    if (StringUtils.hasText(request.getQueryString())) {
      requestURL.append("?");
      requestURL.append(request.getQueryString());
    }
    return requestURL.toString();
  }

  private boolean isRequestedOAuth(HttpSession session) {
    Boolean requested = (Boolean) session.getAttribute(HAS_REQUEST_OAUTH);
    if (requested == null) {
      return false;
    }
    return requested;
  }


}
